package com.mybatis.demo;

import com.mybatis.demo.domain.User;
import com.mybatis.demo.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @Date: 2022/9/1 16:23
 * @Description
 */
public class DemoTest2 {
    public static void main(String[] args) throws IOException {
        // 1、加载配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        // 2、创建 SqlSessionFactoryBuilder 对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 3、创建 SqlSessionFactory 对象
        SqlSessionFactory sqlSessionFactory = builder.build(is);
        // 4、创建 SqlSession 对象
        // 5、获取 UserMapper
        // 执行操作
        User user = new User();
        user.setUsername("测试一级缓存");

        // 第一次查询
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> query = userMapper.query(user);
        System.out.println("第一次查询打印结果: ");
        query.forEach(System.out::println);

        // 相同SQL第二次查询
        // 获取新的 SqlSession
        SqlSession sqlSession2 = sqlSessionFactory.openSession();
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
        query = userMapper2.query(user);
        System.out.println("第二次查询打印结果: ");
        query.forEach(System.out::println);

        // 关闭流
        sqlSession.close();
        is.close();
    }
}
